//
//  ViewController.swift
//  MyKebiao
//
//  Created by David on 2016/12/2.
//  Copyright © 2016年 David. All rights reserved.
//

let TABLE_HEADER_HEIGHT = 20
let TABLE_SIDER_WIDTH = 16
let ITEM_HEIGHT = 56
let KEBIAO_DOMAIN_NAME = "https://hcdstudio.cn/icard"
let KB_DOCUMENT_PATH = "\(DOCUMENT_PATH)/kebiao"
//let DOCUMENT_PATH = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
//let GROUP_URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.KebiaoWiget")!

import UIKit

class KBViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, KBLoginImportDelegate, SetViewDelegate {

    var kebiaoGrid: NSMutableArray?
    var currentWeek: Int = 1
    
    var tableView: UITableView!
    
    var navbar: LLAdaptHideNavBar!
    
    var selWeekBtn: UIButton!
    
    override var title: String?{
        get{
            let btnTitle = selWeekBtn.titleLabel?.text
            if btnTitle != nil {
                return selWeekBtn.titleLabel?.text?.substring(from: btnTitle!.index(btnTitle!.endIndex, offsetBy: -1))
            }
            return nil
        }
        set(t){
            if t != nil{
                let btnTitle = NSMutableAttributedString(string: "\(t!)\u{e61f}")
                btnTitle.addAttribute(NSFontAttributeName, value: UIFont(name: "iconfont", size: 16)!, range: NSMakeRange(t!.characters.count, 1))
                btnTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0, t!.characters.count + 1))
                selWeekBtn.setAttributedTitle(btnTitle, for: .normal)
            }else{
                selWeekBtn.setTitle(t, for: .normal)
            }
            
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
//        print(GROUP_URL)
        
        navbar = LLAdaptHideNavBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64), title: "第0周", navigator: navigationController)
        
        selWeekBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 72, height: 44))
        title = "第1周"
//        let selBtnTitle = NSMutableAttributedString(string: "第0周\u{e61f}")
//        
//        selBtnTitle.addAttribute(NSFontAttributeName, value: UIFont(name: "iconfont", size: 16)!, range: NSMakeRange(3, 1))
//        selBtnTitle.addAttribute(NSForegroundColorAttributeName, value: UIColor.white, range: NSMakeRange(0, 4))
//        selWeekBtn.setAttributedTitle(selBtnTitle, for: .normal)
        
        navbar.navigationItem.titleView = selWeekBtn
        selWeekBtn.addTarget(self, action: #selector(KBViewController.gotoSetView), for: .touchUpInside)
        
        navbar.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(KBViewController.gotoLogin))
        
//        navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: nil, action: nil)
//        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "设置", style: .plain, target: self, action: #selector(KBViewController.gotoSetView))
        
//        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(KBViewController.gotoLogin))
        
        tableView = UITableView(frame: CGRect(x: 0, y: 44, width: view.bounds.width, height: view.bounds.height - 44), style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.allowsSelection = false
        view.addSubview(tableView)
        
        view.addSubview(navbar)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if kebiaoGrid == nil{
            let setting = NSDictionary(contentsOfFile: "\(KB_DOCUMENT_PATH)/setting.plist")
            if setting != nil{
                let format = DateFormatter()
                format.dateFormat = "yyyy-MM-dd"
                let todayWeek = Calendar.current.component(.weekOfYear, from: Date())
                
                let weekNum = setting!.object(forKey: "firstWeek") as! Int
                
                currentWeek = (53 + todayWeek - weekNum)%53 + 1
                
            }
            
            title = "第\(currentWeek)周"
            
            let kebiaoInfos = NSArray(contentsOfFile: "\(KB_DOCUMENT_PATH)/kebiao.plist")
            
            if kebiaoInfos != nil{
                /*
                for item in kebiaoInfos! {
                    let classItem = item as? NSDictionary
                    if classItem != nil{
                        let weekday = classItem?.object(forKey: "weekday") as! String
                        let column = _get_weekday(name: weekday, starter: 1)!
                        
                        let sec = classItem?.object(forKey: "sections") as! String
                        let secInfos = sec.components(separatedBy: ",")
                        let row = Int(secInfos[0])!
                        let length = Int(secInfos[1])! - row + 1
                        
                        let classObj = NSMutableDictionary(dictionary: classItem!)
                        classObj.setValue(length, forKey: "length")
                        
                        let rowArray = kebiaoGrid?.object(at: row-1) as! NSMutableArray
                        let originDic = rowArray.object(at: column) as? NSDictionary
                        if originDic == nil{
                            let originAry = rowArray.object(at: column) as? NSMutableArray
                            if originAry == nil{
                                rowArray.replaceObject(at: column, with: classObj)
                            }else{
                                originAry!.add(classObj)
                                rowArray.replaceObject(at: column, with: originAry!)
                            }
                        }else{
                            let multiClass = NSMutableArray()
                            multiClass.add(originDic!)
                            multiClass.add(classObj)
                            rowArray.replaceObject(at: column, with: multiClass)
                        }
                        
                        
                    }
                }
                */
                kebiaoGrid = NSMutableArray(array: kebiaoInfos!)
            }else{
                kebiaoGrid = NSMutableArray()
                for _ in 0..<12{
                    let row = NSMutableArray()
                    for _ in 0..<7{
                        let dic = NSObject()
                        row.add(dic)
                    }
                    kebiaoGrid?.add(row)
                }
            }
//            print(kebiaoGrid!)
            tableView.reloadData()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.001
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 13
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0{
            return CGFloat(TABLE_HEADER_HEIGHT)
        }
        return CGFloat(ITEM_HEIGHT)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        var cell = tableView.dequeueReusableCell(withIdentifier: "row") as? MyTableViewCell
//        if cell == nil{
          let cell = KBTableViewCell(rowNum: indexPath.row, width: view.bounds.width, reuseID: "row")
            
//        }
        
        if kebiaoGrid != nil{
            if indexPath.row > 0{
                let rowInfos = kebiaoGrid?.object(at: indexPath.row - 1) as! NSArray
                for i in 0..<7{
                    let classItem = rowInfos.object(at: i) as? NSDictionary
                    
                    let classLabel = UILabel()
                    classLabel.font = UIFont.systemFont(ofSize: 12)
                    classLabel.numberOfLines = 8
//                    classLabel.textColor = UIColor.white
                    
                    
                    let colorBG = UIView()
                    
                    
                    
                    if classItem != nil{
                        let weeks = classItem?.object(forKey: "weeks") as! String
                        let weeksRange = weeks.components(separatedBy: "-")
                        if currentWeek >= Int(weeksRange[0])! && currentWeek <= Int(weeksRange[1])! {
                            let eo = classItem?.object(forKey: "eo") as! Int
                            if eo == 0 || (currentWeek%2 == eo%2){
                                let className = classItem?.object(forKey: "class_name") as! String
                                let place = classItem?.object(forKey: "place") as! String
                                
                                let length = classItem?.object(forKey: "length") as! Int
                                let frame = CGRect(x: 0, y: 0, width: (view.bounds.width - CGFloat(TABLE_SIDER_WIDTH))/7, height: CGFloat(length*ITEM_HEIGHT))
                                classLabel.frame = frame
                                colorBG.frame = frame
                                
                                classLabel.text = "\(className)@\(place)"
                                classLabel.sizeToFit()
                                classLabel.lineBreakMode = .byTruncatingMiddle
                                
                                var color = classItem?.object(forKey: "color") as? Int
                                if color == nil {
                                    color = Int(classItem?.object(forKey: "color") as! String)
                                }
                                if color != nil{
                                    colorBG.backgroundColor = _get_color(id: color!)
                                }else{
                                    colorBG.backgroundColor = UIColor.gray
                                }
                                
                                cell.items[i].addSubview(colorBG)
                                colorBG.addSubview(classLabel)
                            }
                        }
                        
                        
                    }else{
                        let classAry = rowInfos.object(at: i) as? NSArray
                        if classAry != nil{
                            for item in classAry!{
                                let classItem = item as? NSDictionary
                                let weeks = classItem?.object(forKey: "weeks") as! String
                                let weeksRange = weeks.components(separatedBy: "-")
                                if currentWeek >= Int(weeksRange[0])! && currentWeek <= Int(weeksRange[1])! {
                                    let eo = classItem?.object(forKey: "eo") as! Int
                                    if eo == 0 || (currentWeek%2 == eo%2){
                                        let className = classItem?.object(forKey: "class_name") as! String
                                        let place = classItem?.object(forKey: "place") as! String
                                        
                                        let length = classItem?.object(forKey: "length") as! Int
                                        let frame = CGRect(x: 0, y: 0, width: (view.bounds.width - CGFloat(TABLE_SIDER_WIDTH))/7, height: CGFloat(length*ITEM_HEIGHT))
                                        classLabel.frame = frame
                                        colorBG.frame = frame
                                        
                                        classLabel.text = "\(className)@\(place)"
                                        classLabel.sizeToFit()
                                        classLabel.lineBreakMode = .byTruncatingMiddle
                                        
                                        var color = classItem?.object(forKey: "color") as? Int
                                        if color == nil {
                                            color = Int(classItem?.object(forKey: "color") as! String)
                                        }
                                        if color != nil{
                                            colorBG.backgroundColor = _get_color(id: color!)
                                        }else{
                                            colorBG.backgroundColor = UIColor.gray
                                        }
                                        
                                        cell.items[i].addSubview(colorBG)
                                        colorBG.addSubview(classLabel)
                                    }
                                }
                            }
                            
                        }
                    }
                }
            }
        }
        
        
        
        return cell
    }
    
    func gotoLogin(){
        
        let loginVC = KBLoginViewController()
        loginVC.delegate = self
        let nav = UINavigationController(rootViewController: loginVC)
        nav.setNavigationBarHidden(true, animated: false)
        present(nav, animated: true, completion: nil)
    }
    
    func gotoSetView(){
        let setVC = SetWeekViewController(currentWeek: currentWeek)
        setVC.delegate = self
        present(setVC, animated: true, completion: nil)
    }
    
    func finishedImportData() {
        kebiaoGrid = nil
    }
    
    func finishedSetWeek(week: Int) {
        currentWeek = week
        title = "第\(currentWeek)周"
        kebiaoGrid = nil
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}
//0x33CCFF, 0x3366FF, 0x6633FF, 0xCC33FF, 0xFF33CC, 0xFF3366, 0xFF6633, 0xFFCC33, 0xCCFF33, 0x66FF33, 0x33FF66, 0x33FFCC, 0x00B8F5, 0x008AB8, 0xF53D00, 0xB82E00,
//0x66FFFF, 0x66B3FF, 0x6666FF, 0xB366FF, 0xFF66FF, 0xFF66B3, 0xFF6666, 0xFFB366, 0xFFFF66, 0xB3FF66, 0x66FF66, 0x66FFB3, 0x29FFFF, 0x00EBEB, 0xFF2929, 0xEB0000,
//  0x66CCFF, 0x667FFF, 0x9966FF, 0xE666FF, 0xFF66CC, 0xFF667F, 0xFF9966, 0xFFE666, 0xCCFF66, 0x7FFF66, 0x66FF99, 0x66FFE6, 0x29B8FF, 0x009CEB, 0xFF7029, 0xEB4E00
let COLOR_TABLE = [
    0xCCFFFF, 0xCCE6FF, 0xCCCCFF, 0xE6CCFF, 0xFFCCFF, 0xFFCCE6, 0xFFCCCC, 0xFFE6CC, 0xFFFFCC, 0xE6FFCC, 0xCCFFCC, 0xCCFFE6, 0x8FFFFF, 0x52FFFF, 0xFF8F8F
    , 0xFFFFCC, 0xE6FFCC, 0xCCFFCC, 0xCCFFE6, 0xCCFFFF, 0xCCE6FF, 0xCCCCFF, 0xE6CCFF, 0xFFCCFF, 0xFFCCE6, 0xFFCCCC, 0xFFE6CC, 0xFFFF8F, 0xFFFF52, 0x8F8FFF
    , 0xCCFFCC, 0xCCFFE6, 0xCCFFFF, 0xCCE6FF, 0xCCCCFF, 0xE6CCFF, 0xFFCCFF, 0xFFCCE6, 0xFFCCCC, 0xFFE6CC, 0xFFFFCC, 0xE6FFCC, 0x8FFF8F, 0x52FF52, 0xFF8FFF
]



func _get_color(id: Int) -> UIColor{
    let colorHex = COLOR_TABLE[id]
    return UIColor(
        red: CGFloat((colorHex & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((colorHex & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(colorHex & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
    
}


